package com.windaka.elements.utils;


import java.util.HashMap;
import java.util.Map;

/**
 * 线程容器
 * @author song
 * @date 17:45 2021/9/3
**/
public class ThreadLocalUtils {

    private ThreadLocalUtils() {}

    /**
     * 线程容器
     * @date 17:47 2021/9/3
    **/
    private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT =
            new MapThreadLocal();

    /**
     * 容器的大小 (要合理的配置)
     * @date 18:37 2021/9/3
     **/
    private static final int THREAD_LOCAL_SIZE = 100;
    
    /**
     * get方法 从ThreadLocal先取Map再取值
     * @author song
     * @date 18:12 2021/9/3
    **/
    public static Object get(String key) {
        return getContextMap().get(key);
    }
    
    /**
     * put
     * @author song
     * @date 18:12 2021/9/3
    **/
    public static void put(String key, Object value) {
        getContextMap().put(key, value);
    }
    
    /**
     * remove
     * @author song
     * @date 18:12 2021/9/3
    **/
    public static Object remove(String key) {
        return getContextMap().remove(key);
    }
    
    /**
     * remove
     * @author song
     * @date 18:12 2021/9/3
    **/
    public static void remove() {
        getContextMap().clear();
    }
    
    /**
     * clear
     * @author song
     * @date 18:12 2021/9/3
    **/
    public static void clear() {
        THREAD_CONTEXT.remove();
    }
    
    /**
     * 获取Map
     * @author song
     * @date 18:12 2021/9/3
    **/
    private static Map<String, Object> getContextMap() {
        return THREAD_CONTEXT.get();
    }

    /**
     * 用HashMap可以规避null的问题
     * @author song
     * @date 18:37 2021/9/3
    **/
    private static class MapThreadLocal extends ThreadLocal<Map<String, Object>> {
        @Override
        protected Map<String, Object> initialValue() {
            return new HashMap<>(THREAD_LOCAL_SIZE);
        }
    }

}
